
document.addEventListener('DOMContentLoaded', () => {
    const selectedCourseList = document.getElementById('selectedCourseList');

    // 退选按钮点击事件
    selectedCourseList.addEventListener('click', (e) => {
        const btn = e.target.closest('.delete-btn');
        if (btn) {
            const selectionId = btn.dataset.selectionId;
            const courseName = btn.closest('tr').querySelector('td:nth-child(2)').textContent.trim();

            // 显示退选确认提示（从顶部中间弹出）
            showConfirmToast(selectionId, courseName, btn);
        }
    });

    // 显示确认退选提示（从顶部中间弹出）
    function showConfirmToast(selectionId, courseName, triggerButton) {
        // 创建确认提示元素
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 p-4 bg-yellow-100 border border-yellow-200 rounded-lg shadow-lg transition-all duration-300 ease-in-out z-50 opacity-0 translate-y-[-20px]';
        toast.innerHTML = `
            <div class="flex items-center justify-between w-full gap-4">
                <div class="flex items-center gap-2">
                    <i class="fa fa-question-circle text-yellow-500"></i>
                    <span>确认要退选 <strong>${courseName}</strong> 吗？</span>
                </div>
                <div class="flex items-center gap-2">
                    <button class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors confirm-btn">
                        确认退选
                    </button>
                    <button class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors cancel-btn">
                        取消
                    </button>
                </div>
            </div>
        `;

        // 添加到文档并显示
        document.body.appendChild(toast);
        setTimeout(() => {
            toast.classList.remove('opacity-0', 'translate-y-[-20px]');
        }, 10);

        // 添加事件监听
        toast.querySelector('.confirm-btn').addEventListener('click', () => {
            handleDropCourse(selectionId, courseName, triggerButton, toast);
        });

        toast.querySelector('.cancel-btn').addEventListener('click', () => {
            hideToast(toast);
        });

        // 10秒后自动隐藏
        setTimeout(() => {
            hideToast(toast);
        }, 10000);
    }

    // 处理退选请求
    function handleDropCourse(selectionId, courseName, triggerButton, toastElement) {
        // 隐藏确认提示
        hideToast(toastElement);

        // 显示加载状态
        if (triggerButton) {
            const originalHTML = triggerButton.innerHTML;
            triggerButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 处理中...';
            triggerButton.disabled = true;
        }

        // 发送退选请求
        fetch(`/student/course/drop/${selectionId}`, { method: 'POST' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功提示（从顶部中间弹出）
                    showToast(`已成功退选课程：${courseName}`, 'success');

                    // 从列表中移除课程行
                    const row = document.querySelector(`[data-selection-id="${selectionId}"]`);
                    if (row) {
                        row.classList.add('opacity-0');
                        setTimeout(() => {
                            row.remove();
                            updateCourseCount();
                        }, 300);
                    }
                } else {
                    // 显示错误提示
                    showToast(data.message || '退选失败，请重试', 'error');

                    // 恢复按钮状态
                    if (triggerButton) {
                        triggerButton.innerHTML = originalHTML;
                        triggerButton.disabled = false;
                    }
                }
            })
            .catch(error => {
                // 显示错误提示
                showToast('退选失败，请检查网络连接', 'error');
                console.error('退选请求失败:', error);

                // 恢复按钮状态
                if (triggerButton) {
                    triggerButton.innerHTML = originalHTML;
                    triggerButton.disabled = false;
                }
            });
    }

    // 显示提示消息（从顶部中间弹出）
    function showToast(message, type) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = `fixed top-4 left-1/2 transform -translate-x-1/2 p-4 rounded-lg shadow-lg transition-all duration-300 ease-in-out z-50 opacity-0 translate-y-[-20px]`;

        // 设置样式
        if (type === 'success') {
            toast.classList.add('bg-green-100', 'border', 'border-green-200', 'text-green-800');
            toast.innerHTML = `
                <div class="flex items-center gap-2">
                    <i class="fa fa-check-circle text-green-500"></i>
                    <span>${message}</span>
                </div>
            `;
        } else {
            toast.classList.add('bg-red-100', 'border', 'border-red-200', 'text-red-800');
            toast.innerHTML = `
                <div class="flex items-center gap-2">
                    <i class="fa fa-exclamation-circle text-red-500"></i>
                    <span>${message}</span>
                </div>
            `;
        }

        // 添加到文档并显示
        document.body.appendChild(toast);
        setTimeout(() => {
            toast.classList.remove('opacity-0', 'translate-y-[-20px]');
        }, 10);

        // 3秒后隐藏
        setTimeout(() => {
            toast.classList.add('opacity-0', 'translate-y-[-20px]');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // 隐藏提示
    function hideToast(toastElement) {
        if (toastElement) {
            toastElement.classList.add('opacity-0', 'translate-y-[-20px]');
            setTimeout(() => toastElement.remove(), 300);
        }
    }

    // 更新课程计数
    function updateCourseCount() {
        const countElement = document.querySelector('h2.text-xl');
        if (countElement) {
            const count = document.querySelectorAll('#selectedCourseList tr').length;
            const regex = /共\s*\d+\s*门/;
            if (regex.test(countElement.textContent)) {
                countElement.textContent = countElement.textContent.replace(regex, `共 ${count} 门`);
            }
        }

        // 检查是否没有课程了
        const courseList = document.getElementById('selectedCourseList');
        if (courseList && courseList.children.length === 0) {
            courseList.innerHTML = `
                <tr>
                    <td colspan="7" class="px-6 py-12 text-center">
                        <div class="mb-6">
                            <i class="fa fa-book-open text-4xl text-primary/10 animate-spin"></i>
                        </div>
                        <h3 class="text-lg font-bold text-gray-800 mb-2">尚未选择任何课程</h3>
                        <p class="text-gray-500 mb-6">点击 <a href="${url_for('student.course_selection')}" class="text-primary hover:underline">这里</a> 查看可选课程</p>
                    </td>
                </tr>
            `;
        }
    }

    // 将核心函数暴露到全局作用域（可选，仅用于内联事件处理）
    window.handleDropCourse = handleDropCourse;
});
